马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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?
/**
* 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) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
help(root,list);
return list;
}
public void help(TreeNode root, List<Integer> list){
if(root == null) return;
if(root.left == null && root.right == null){
list.add(root.val);
}
else if(root.left != null && root.right == null) {
help(root.left, list);
list.add(root.val);
}
else if(root.right != null && root.left == null){
list.add(root.val);
help(root.right,list);
}
else{
help(root.left,list);
list.add(root.val);
help(root.right,list);
}
}
}
/**
* 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) {
List<Integer> list = new ArrayList<Integer>();
Stack <TreeNode> stack = new Stack<>();
TreeNode c = root;
while(c != null || !stack.isEmpty()){
while(c != null){
stack.push(c);
c = c.left;
}
c = stack.pop();
list.add(c.val);
c = c.right;
}
return list;
}
}
|