94. Binary Tree Inorder Traversal

来源:互联网 发布:mac安装axure出错 编辑:程序博客网 时间:2024/06/03 15:35

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

For example:
Given binary tree [1,null,2,3],

   1    \     2    /   3

return [1,3,2].

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

Subscribe to see which companies asked this question.


Java Code:

/** * Definition for a binary tree node. * 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<>();        if (null == root) {            return result;        }                Stack<TreeNode> stack = new Stack<>();        TreeNode node = root;                while (node != null || !stack.isEmpty()) {            if (null != node) {                stack.push(node);                node = node.left;            } else {                node = stack.pop();                if (node != null) {                    result.add(node.val);                    node = node.right;                }            }        }                 return result;    }}


0 0
原创粉丝点击