树的定义
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
递归三要素
144.二叉树的前序遍历(opens new window)
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
private void preorder(TreeNode root, List<Integer> result){
if(root == null)
return;
result.add(root.val);
preorder(root.left,result);
preorder(root.right,result);
}
}
145.二叉树的后序遍历(opens new window)
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
postorder(root, result);
return result;
}
private void postorder(TreeNode root, List<Integer> result){
if(root == null)
return;
postorder(root.left,result);
postorder(root.right,result);
result.add(root.val);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
inorder(root, result);
return result;
}
private void inorder(TreeNode root, List<Integer> result){
if(root == null)
return;
inorder(root.left,result);
result.add(root.val);
inorder(root.right,result);
}
}
使用栈,因为栈是后入先出,所以使用栈来记录结点,先押入跟结点,在押入右结点和左节点,按照出栈顺序访问元素
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode temp = stack.pop();
//left后入栈会先出栈,因为是根左右
result.add(temp.val);
if (temp.right != null)
stack.push(temp.right);
if (temp.left != null)
stack.push(temp.left);
}
return result;
}
}
与前序遍历基本一致
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode temp = stack.pop();
result.add(temp.val);
if (temp.left != null){
stack.push(temp.left);
}
if (temp.right != null){
stack.push(temp.right);
}
}
Collections.reverse(result);
return result;
}
}
单独的思路,因为不能先将根压入栈,那么如果先将left入栈会导致指针的丢失,所以要先找到左子树为空的,也就是下一个元素就是当前的栈顶,即当前子树的根结点
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if (root == null)
return result;
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || cur != null){
if (cur != null){//此时要找到左子树的底部
stack.push(cur);
cur = cur.left;
}else {//当前结点没有了左子树,那么当前没有左子树的跟结点就是栈顶
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
更多【windows-训练营十四天(二叉树的遍历)】相关视频教程:www.yxfzedu.com