Binary Tree Inorder Traversal (Java)

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].

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

Source递归

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	List st = new ArrayList();
    public List inorderTraversal(TreeNode root){
    	
    	
    	if(root == null) return st;
    	
    	
    	if(root.left != null) inorderTraversal(root.left);
    	st.add(root.val);
    	if(root.right != null) inorderTraversal(root.right);

    	return st;
    }
}


Test

    public static void main(String[] args){
    	TreeNode a = new TreeNode(1);
    	a.left = new TreeNode(2);
    	a.right = new TreeNode(3);
    	a.left.left = new TreeNode(4);
    	a.left.right = new TreeNode(5);
    	a.right.left = new TreeNode(6);
    	a.right.right = new TreeNode(7);
    	
    	System.out.println(new Solution().inorderTraversal(a));
  
    }


Source非递归

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List inorderTraversal(TreeNode root) {
    	List st = new ArrayList();
    	if(root == null) return st;
    	Stack l = new Stack();
    	
    	
    	while(!l.isEmpty() || root != null ){  //注意判断信息不止是l不为空
    		if(root != null){
    			l.push(root);
    			root = root.left;
    		}
    		else{
    			TreeNode a = l.pop();
    			st.add(a.val);       //注意此时才添加值,即pop了再添加
    			root = a.right;
    		}
    	}
        return st;
    }
}



你可能感兴趣的:(DFS,LeetCode,medium,Tree,Stack)