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

leetcode-94:Binary Tree Inorder Traversal (Java)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    
    // 非遞迴
     public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        TreeNode curNode = root;
        
        while( !stack.isEmpty() || curNode!=null){
            while(curNode != null){
                stack.push(curNode);
                curNode = curNode.left;
            }
            
            if( !stack.isEmpty()){
                curNode = stack.pop();
                list.add(curNode.val);
                curNode = curNode.right;
            }
        }
        
        return list;
    }
    
    /**遞迴呼叫
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        inorder(root,list);
        return list;
    }
    
    public void inorder(TreeNode root,List<Integer> list){
        if(root == null)
            return;
        
        if(root.left != null){
            inorder(root.left,list);
        }
        list.add(root.val);
        // print(root.val);
        if(root.right != null){
            inorder(root.right,list);
        }
    }
    */
}