LeetCode 58 Binary Tree Inorder Traversal

来源:互联网 发布:linux jira6.3.6 安装 编辑:程序博客网 时间:2024/05/21 09:24

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?

分析:

和先序和后序一样,利用一个栈,把沿途左孩子压栈。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> inorderTraversal(TreeNode root) {        List<Integer> result = new ArrayList<Integer>();        if(root==null) return result;        Stack<TreeNode> st = new Stack<TreeNode>();        TreeNode p = root;        while(p != null || st.size()>0){            while(p != null){                st.push(p);                p = p.left;            }            if(st.size()>0){                TreeNode temp = st.pop();                result.add(temp.val);                p = temp.right;            }        }        return result;    }}


0 0
原创粉丝点击