Leetcode--144. 二叉树的前序遍历(迭代递归)
給定一個二叉樹,返回它的?前序?遍歷。
?示例:
輸入: [1,null,2,3] ?
? ?1
? ? \
? ? ?2
? ? /
? ?3?
輸出: [1,2,3]
進階:?遞歸算法很簡單,你可以通過迭代算法完成嗎?
代碼:
迭代:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????public?List<Integer>?preorderTraversal(TreeNode?root)?{
????????List<Integer>?result?=?new?LinkedList<>();
????????Stack<TreeNode>?stack?=?new?Stack<>();
????????if(root==null){
????????????return?result;
????????}
????????while(!stack.isEmpty()||root!=null){
????????????if(root!=null){
????????????????result.add(root.val);
????????????????stack.add(root);
????????????????root?=?root.left;
????????????}else{
????????????????root?=?stack.pop();
????????????????root?=?root.right;
????????????}
????????}
????????return?result;
????}
}
?
遞歸:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????public?List<Integer>?preorderTraversal(TreeNode?root)?{
????????List<Integer>?list?=?new?ArrayList<Integer>();
????????return?fun(root,list);
????}
????public?List<Integer>?fun(TreeNode?root,List<Integer>?list)
????{
????????if(root!=null)
????????{
????????????list.add(root.val);
????????????if(root.left!=null)
????????????{
????????????????fun(root.left,list);
????????????}
????????????if(root.right!=null)
????????????{
????????????????fun(root.right,list);
????????????}
????????}
????????return?list;
????????
????}
}
總結
以上是生活随笔為你收集整理的Leetcode--144. 二叉树的前序遍历(迭代递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode--188. 买卖股票的
- 下一篇: 牛客网--单词倒排(Java)