Binary Tree Inorder Traversal:中序遍歷二叉樹,不使用深度優先遍歷
阿新 • • 發佈:2019-01-03
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?
思路:遍歷二叉樹,可以使用遞迴遍歷、使用棧模擬遞迴迭代遍歷、使用線索二叉樹的Morris遍歷。我選擇第三種。Morris遍歷參考:Morris
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { //使用線索二叉樹,Morris遍歷 public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if(root==null) return res; TreeNode n = root; TreeNode pre = null; while(n!=null){ if(n.left==null){//當前節點的左節點為空,則列印當前節點,並設定當前節點為當前節點的右節點 res.add(n.val); n = n.right; }else{//否則,找到當前節點的中序遍歷前驅節點,即當前節點左孩子的最右側孩子 pre = n.left; while(pre.right!=null&&pre.right!=n) pre = pre.right; if(pre.right == null){//如果前驅節點為空,則設定其右節點為當前節點(設定線索),並將當前節點設為當前節點的左孩子 pre.right = n; n = n.left; }else{//否則,說明當前節點的左分支已經遍歷過,恢復成原樣,列印,並設定當前節點為當前節點的右孩子 pre.right = null; res.add(n.val); n = n.right; } } } return res; } }