Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3],
1
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
題意:中序遍歷一個二叉樹,以數組形式返回遍歷結果。
思路:中序遍歷就是按照左中右的順序遍歷數組,因此我們可以先遍歷根節點的左子樹,然后遍歷根節點,最后遍歷根節點的右子樹。如果左子樹或者右子樹仍然是非葉子幾點,我們可以用上面的方法遞歸對左右子樹進行調用。直到遍歷到的節點是一個葉子節點,我們將它加入到list中。
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
dfs(root, res);
return res;
}
public void dfs(TreeNode root, List<Integer> res) {
if (root.left == null && root.right == null) {
res.add(root.val);
return;
}
if (root.left != null) {
dfs(root.left, res);
}
res.add(root.val);
if (root.right != null) {
dfs(root.right, res);
}
}
題目最后要求不用遞歸的解法。因為是中序遍歷,輸出完左子樹后還要再輸出自己的根節點,所以我們需要一個數據結構能夠記得之前遍歷過的根節點,由此想到了用棧。
第一步是要找到最左節點,就從根節點開始不停向左找下去,如果自己還有左節點,就把自己加入到棧中
第二步,彈出當前棧頂,這就是最左節點了
第三步,如果當前彈出元素還有右節點,那么證明此節點有右子樹,需要把右節點加到棧中,然后對這個右子樹進行中序遍歷;如果沒有右節點,則需要遍歷到自己的父節點了。
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while(cur!=null || !stack.empty()){
while(cur!=null){
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}
return list;
}