二叉树前序遍历递归法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
TreeNode cur = new TreeNode();
cur = root;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
traversal(cur,arrayList);
return arrayList;
}
public void traversal(TreeNode cur,List arrayList){
if(cur == null){
return;
}
arrayList.add(cur.val);
traversal(cur.left,arrayList);
traversal(cur.right,arrayList);
}
}
前序遍历迭代法
注意要判断root是否为null,否则会报错
public List<Integer> preorderTraversal(TreeNode root) {
TreeNode cur = new TreeNode();
cur = root;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// traversal(cur,arrayList);
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null){
return arrayList;
}
stack.push(root);
while(!stack.isEmpty()){
cur = stack.peek();
arrayList.add(cur.val);
stack.pop();
if(cur.right!= null){
stack.push(cur.right);
}
if(cur.left !=null){
stack.push(cur.left);
}
}
return arrayList;
}
中序遍历迭代法:(还可以进一步简化,可以参看代码随想录)
public List<Integer> preorderTraversal(TreeNode root) {
TreeNode cur = new TreeNode();
cur = root;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
// traversal(cur,arrayList);
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null){
return arrayList;
}
stack.push(root);
while(!stack.isEmpty()){
cur = stack.peek();
arrayList.add(cur.val);
stack.pop();
if(cur.right!= null){
stack.push(cur.right);
}
if(cur.left !=null){
stack.push(cur.left);
}
}
return arrayList;
}
后序遍历:反转result数组
统一迭代法暂时先不看了。后面有机会再看