每天1題演算法題(1)-二叉樹的中序遍歷
阿新 • • 發佈:2020-09-16
給定一個二叉樹,返回它的中序遍歷。
輸入: [1,null,2,3] 1 \ 2 / 3 輸出: [1,3,2]
1.最簡單也是最直接的,直接用遞迴演算法實現
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList(); dfs(root,result); return result; }public void dfs(TreeNode root, List list) { if(root == null) { return; } dfs(root.left, list); list.add(root.val); dfs(root.right, list); } }
缺點:
效率低下
2.用迭代模擬遞迴
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList(); Stack<TreeNode> stack = new Stack(); while(stack.size() > 0 || root != null) { if(root != null) { stack.add(root); root = root.left; } else { root = stack.pop(); result.add(root.val); root = root.right; } } return result; } }
缺點:
效率低下
3.莫里斯遍歷
用遞迴和迭代的方式都使用了輔助的空間,而莫里斯遍歷的優點是沒有使用任何輔助空間。
缺點是改變了整個樹的結構,強行把一棵二叉樹改成一段連結串列結構。
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); TreeNode pre = null; while(root!=null) {//如果左節點不為空,就將當前節點連帶右子樹全部掛到 //左節點的最右子樹下面 if(root.left!=null) { pre = root.left; while(pre.right!=null) { pre = pre.right; } pre.right = root; //將root指向root的left TreeNode tmp = root; root = root.left; tmp.left = null; //左子樹為空,則列印這個節點,並向右邊遍歷 } else { res.add(root.val); root = root.right; } } return res; } }
進階