1. 程式人生 > >leetcode:(94) Binary Tree Inorder Traversal(java)

leetcode:(94) Binary Tree Inorder Traversal(java)

package HashTable;

/**
 * 題目:
 *      Given a binary tree, return the inorder traversal of its nodes' values.
 * 解題思路:
 *      從根節點開始,先將根節點壓入棧,然後再將其所有左子結點壓入棧,然後取出棧頂節點,儲存節點值,
 *      再將當前指標移到其右子節點上,若存在右子節點,則在下次迴圈時又可將其所有左子結點壓入棧中。
 *      這樣就保證了訪問順序為左-根-右
 */

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class InorderTraversal_94_1019 {
    public List<Integer> InorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            cur = stack.pop();
            result.add(cur.val);
            cur = cur.right;
        }

        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);

        root.right = node1;
        node1.left = node2;

        InorderTraversal_94_1019 test = new InorderTraversal_94_1019();
        List<Integer> result = test.InorderTraversal(root);
        System.out.println(result);
    }
}