赞
踩
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
preOrder(root, result);
return result;
}
public void preOrder(TreeNode root, List<Integer> result){
if(root == null) return;
result.add(root.val);
preOrder(root.left, result);
preOrder(root.right, result);
}
}
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inOrder(root, result);
return result;
}
public 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> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
postOrder(root, result);
return result;
}
public 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> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root == null) return result;
stack.push(root);
while(!stack.empty()){
TreeNode tmp = stack.pop();
result.add(tmp.val);
if(tmp.right != null) stack.push(tmp.right);
if(tmp.left != null) stack.push(tmp.left);
}
return result;
}
}
因为前序遍历的顺序是中左右,先访问的元素是中间节点,要处理的元素也是中间节点,所以才能写出相对简洁的代码,因为要访问的元素和要处理的元素顺序是一致的,都是中间节点。
中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树左面的最底部,再开始处理节点(也就是在把节点的数值放进result数组中),这就造成了处理顺序和访问顺序是不一致的。
那么在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if(root == null) return result; Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; while(cur != null || !stack.empty()){ if(cur != null){ stack.push(cur); cur = cur.left; }else{ cur = stack.pop(); result.add(cur.val); cur = cur.right; } } } }
class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); if(root == null) return result; stack.push(root); while(!stack.empty()){ TreeNode tmp = stack.pop(); result.add(tmp.val); if(tmp.left != null) stack.push(tmp.left); if(tmp.right != null) stack.push(tmp.right); } Collections.reverse(result); return result; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。