leetcode 144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
二叉树的前序遍历,非递归的写法考的比较多,方法很简单,就是把跟节点加进来,依次把右子树和左子树压入栈内,弹出的时候肯定是先弹出左子树,然后再弹出右子树,
达到先遍历跟节点,再依次遍历左子树和右子树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> preorder = new ArrayList<Integer>(); if (root == null) { return preorder; } stack.push(root); while (!stack.empty()) { TreeNode node = stack.pop(); preorder.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return preorder; } }
递归的方法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); traversal(root, result); return result; } private void traversal(TreeNode root, List<Integer> result) { if (root == null) { return; } result.add(root.val); traversal(root.left, result); traversal(root.right, result); } }
先把root压栈来,
栈非空进循环。
弹栈进数组,
右非空压栈,
左非空压栈。