94. Binary Tree Inorder Traversal

来源:互联网 发布:儿童阅读软件下载 编辑:程序博客网 时间:2024/05/22 14:34

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

  public List<Integer> inorderTraversal(TreeNode root) {       List<Integer> lst = new ArrayList<Integer>();        if(root == null)            return lst;         Stack<TreeNode> stack = new Stack<TreeNode>();        //define a pointer to track nodes        TreeNode p = root;        while(!stack.empty() || p != null){            // if it is not null, push to stack            //and go down the tree to left            if(p != null){                stack.push(p);                p = p.left;            // if no left child            // pop stack, process the node            // then let p point to the right            }else{                TreeNode t = stack.pop();                lst.add(t.val);                p = t.right;            }        }        return lst;    }
0 0
原创粉丝点击