[LeetCode-JAVA] 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].

思路:题中规定用循环代替递归求解,用辅助stack来存储遍历到的节点,如果不为空则入栈,否则出栈赋值,并指向其右节点。

[LeetCode-JAVA] Binary Tree Inorder Traversal

 

代码:

public class Solution {

    public List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> req = new ArrayList<Integer>();

        

        if(root == null)

            return req;

        Stack<TreeNode> stack = new Stack<TreeNode>();

        

        while(!stack.isEmpty() || root != null){

            if(root != null){

                stack.push(root);

                root = root.left;

            }else{

                TreeNode temp = stack.pop();

                req.add(temp.val);

                root = temp.right;       //最重要的一步

            }

            

        }

        

        return req;

    }

}

参考链接: http://www.programcreek.com/2012/12/leetcode-solution-of-binary-tree-inorder-traversal-in-java/

你可能感兴趣的:(LeetCode)