美文网首页
中序遍历二叉树

中序遍历二叉树

作者: 小白学编程 | 来源:发表于2018-09-24 09:26 被阅读0次

递归

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<Integer>();
        inorder(root,list);
        return list;
    }
    
    public void inorder(TreeNode root,List<Integer> list){
        //List<Integer> list=new ArrayList<Integer>();
        if(root==null){
            return ;
        }
        inorder(root.left,list);
        
        list.add(root.val);
        inorder(root.right,list);
        
    }
}

迭代

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list=new ArrayList<Integer>();
        Stack<TreeNode> stack=new Stack<TreeNode>();
        
        TreeNode cur=root;
        while(!stack.isEmpty()||cur!=null){
            while(cur!=null){
                stack.push(cur);
                cur=cur.left;
            }
            
            cur=stack.pop();
            list.add(cur.val);
            cur=cur.right;
        }
        
        return list;
    }
}

相关文章

网友评论

      本文标题:中序遍历二叉树

      本文链接:https://www.haomeiwen.com/subject/mgecoftx.html