您的位置:首页 > 其它

【LeetCode】Binary Tree Inorder Traversal 二叉树中序遍历递归以及非递归算法

2014-05-07 18:21 447 查看
Binary Tree Inorder Traversal

Total Accepted: 16494 Total Submissions: 47494

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.

【解题思路】

1、递归

Java AC

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ArrayList<Integer> list;
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        list = new ArrayList<Integer>();
        inOrder(root);
        return list;
    }
    private void inOrder(TreeNode root){
        if(root == null){
            return;
        }
        inOrder(root.left);
        list.add(root.val);
        inOrder(root.right);
    }
}
2、非递归

栈存储节点,当左孩子不为空,一直入栈。否则出栈,同时将栈顶元素存入list中,针对当前节点右孩子做同样操作。

Java AC

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ArrayList<Integer> list;
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        list = new ArrayList<Integer>();
        inOrder(root);
        return list;
    }
    private void inOrder(TreeNode root){
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while(root != null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            if(!stack.isEmpty()){
                root = stack.pop();
                list.add(root.val);
                root = root.right;
            }
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐