`
hcx2013
  • 浏览: 88935 次
社区版块
存档分类
最新评论

Binary Tree Inorder Traversal

 
阅读更多

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

 

/**
 * 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> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

	private void dfs(TreeNode root, List<Integer> res) {
		if (root != null) {
        	dfs(root.left, res);
        	res.add(root.val);
        	dfs(root.right, res);
        }
	}
}

 

/**
 * 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> res = new ArrayList<>();
    	if (root == null) {
    		return res;
    	}
    	LinkedList<TreeNode> stack = new LinkedList<>();
    	while (root!=null || !stack.isEmpty()) {
    		if (root!=null) {
    			stack.push(root);
    			root = root.left;
    		} else {
    			root = stack.pop();
    			res.add(root.val);
    			root = root.right;
    		}
    	}
    	return res;
    }
}

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics