Given a binary tree, return the inorder traversal of its nodes‘ values.
Example
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Challenge
Can you do it without recursion?
两种做法:
1. 使用递归, 思路比较直接,不多说了
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return result; helper(root, result); return result; } public void helper(TreeNode root, ArrayList<Integer> result){ if(root == null) return; else{ helper(root.left, result); result.add(root.val); helper(root.right, result); return; } } }
2. 不使用递归的方法,使用一个stack,维护一个reference p
当p非null时,将p入栈,p指向左子树
当p为null时,栈顶元素出栈,加入arraylist,p再指向右子树
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return result; TreeNode p = root; Stack<TreeNode> stack = new Stack<TreeNode>(); while(p != null || !stack.isEmpty()){ if(p != null){ stack.push(p); p = p.left; } else{ p = stack.pop(); result.add(p.val); p = p.right; } } return result; } }
时间: 2024-12-15 04:12:24