Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
二叉树的先序遍历。
树的几种遍历,网上有一个不错的例子,一个树给了多种遍历的结果
Depth First Traversals:
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1Breadth First or Level Order Traversal : 1 2 3 4 5
对于这题,我在网上又找了一个更复杂的树及其遍历结果,如下图(reference)
二叉树的遍历有多种方式,此题是要求用先序遍历。我自己总结的先序遍历的特点是根 - 左 - 右。即如果只有一个根节点和两个子节点的情形下(比如[1, 2, 3]),输出结果应该也是[1, 2, 3]。这题迭代和递归都需要掌握。遍历的时候会用到栈,因为栈是先进后出,所以放进栈的时候记得要逆向,先放右孩子再放左孩子。两种做法的时间复杂度是O(n),空间复杂度是O(h)。h是树的高度。
迭代
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {number[]} 4 */ 5 var preorderTraversal = function(root) { 6 // corner case 7 if (!root) return []; 8 9 // normal case 10 let result = []; 11 // let stack = [root]; 12 let stack = []; 13 stack.push(root); 14 while (stack.length) { 15 var node = stack.pop(); 16 result.push(node.val); 17 if (node.right) stack.push(node.right); 18 if (node.left) stack.push(node.left); 19 } 20 return result; 21 };
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> preorderTraversal(TreeNode root) { 12 List<Integer> res = new ArrayList<>(); 13 if (root == null) { 14 return res; 15 } 16 Stack<TreeNode> stack = new Stack<>(); 17 stack.push(root); 18 while (!stack.isEmpty()) { 19 TreeNode cur = stack.pop(); 20 res.add(cur.val); 21 if (cur.right != null) { 22 stack.push(cur.right); 23 } 24 if (cur.left != null) { 25 stack.push(cur.left); 26 } 27 } 28 return res; 29 } 30 }
递归
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @return {number[]} 4 */ 5 var preorderTraversal = function(root) { 6 let res = []; 7 if (root === null) { 8 return res; 9 } 10 helper(res, root); 11 return res; 12 }; 13 14 var helper = function(res, root) { 15 if (root === null) return; 16 res.push(root.val); 17 helper(res, root.left); 18 helper(res, root.right); 19 };
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public List<Integer> preorderTraversal(TreeNode root) { 12 List<Integer> res = new ArrayList<>(); 13 if (root == null) return res; 14 helper(res, root); 15 return res; 16 } 17 18 private void helper(List<Integer> res, TreeNode root) { 19 if (root == null) return; 20 res.add(root.val); 21 helper(res, root.left); 22 helper(res, root.right); 23 } 24 }
树的遍历
94. Binary Tree Inorder Traversal
144. Binary Tree Preorder Traversal