Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
61 lines (50 loc) · 1.39 KB

File metadata and controls

61 lines (50 loc) · 1.39 KB
Copy raw file
Download raw file
Outline
Edit and raw actions

Difficulty: Medium

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

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

Solution

Language: Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
​
        TreeNode p = root;
        while (p != null || !stack.isEmpty()) {
            // 一直向左,把所有节点压栈
            while (p != null) {
                stack.push(p);
                p = p.left;
            }
            // 压栈结束,元素出栈
            p = stack.pop();
            // 打印 value
            result.add(p.val);
            // 对右子树做同样的操作
            p = p.right;
        }
        return result;
    }
}

LH5Tf6

Morty Proxy This is a proxified and sanitized view of the page, visit original site.