• Binary Tree Inorder Traversal


    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?

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ArrayList<Integer> inorderTraversal(TreeNode root) {
            if (root==null){
                return new ArrayList<Integer>();
            }
            ArrayList<Integer> ret = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while (!stack.empty()) {
                TreeNode p = null;
                //找到最左子树的叶子
                while (stack.peek() != null){
                    p = stack.peek();
                    stack.push(p.left);
                    p = p.left;
                }
                //把最后叶子节点left的null弹出
                stack.pop();
                //如果是最右子树的叶子节点的时候栈就空了
                if (stack.empty()){
                    return ret;
                }
                p = stack.pop();
                ret.add(p.val);
                //把右子树当做根节点,找最左
                stack.push(p.right);
            }
            return ret;
        }
    }
  • 相关阅读:
    牛客练习赛24 E:青蛙(最短路)
    菜根谭#10
    菜根谭#9
    菜根谭#8
    菜根谭#7
    菜根谭#6
    菜根谭#5
    菜根谭#4
    菜根谭#3
    菜根谭#2
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506865.html
Copyright © 2020-2023  润新知