代码随想录---二叉树

二叉树前序遍历递归法

/**
 * 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数组

统一迭代法暂时先不看了。后面有机会再看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值