144. Binary Tree Preorder Traversal(二叉树的前序遍历)

简介: 题目练习二叉树的前序遍历

 题目地址:- LeetCode

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?

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [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; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
Stack<TreeNode>stack=newStack<>();
while (root!=null||!stack.isEmpty()) {
while (root!=null) {
stack.push(root);
list.add(root.val);
root=root.left;
            }
root=stack.pop();
root=root.right;
        }
returnlist;
    }
}

image.gif

image.gif


递归版:

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
preorder(list, root);
returnlist;
    }
publicvoidpreorder(List<Integer>list, TreeNoderoot) {        
if (root==null) {
return ;
        }
list.add(root.val);
preorder(list, root.left);
preorder(list, root.right);
    }
}

image.gif

image.gif



Debug code in playground:

/* -----------------------------------*  WARNING:* -----------------------------------*  Your code may fail to compile*  because it contains public class*  declarations.*  To fix this, please remove the*  "public" keyword from your class*  declarations.*//*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/classSolution {
publicList<Integer>preorderTraversal(TreeNoderoot) {
List<Integer>list=newArrayList<>();
preorder(list, root);
returnlist;
    }
publicvoidpreorder(List<Integer>list, TreeNoderoot) {        
if (root==null) {
return ;
        }
list.add(root.val);
preorder(list, root.left);
preorder(list, root.right);
    }
}
publicclassMainClass {
publicstaticTreeNodestringToTreeNode(Stringinput) {
input=input.trim();
input=input.substring(1, input.length() -1);
if (input.length() ==0) {
returnnull;
        }
String[] parts=input.split(",");
Stringitem=parts[0];
TreeNoderoot=newTreeNode(Integer.parseInt(item));
Queue<TreeNode>nodeQueue=newLinkedList<>();
nodeQueue.add(root);
intindex=1;
while(!nodeQueue.isEmpty()) {
TreeNodenode=nodeQueue.remove();
if (index==parts.length) {
break;
            }
item=parts[index++];
item=item.trim();
if (!item.equals("null")) {
intleftNumber=Integer.parseInt(item);
node.left=newTreeNode(leftNumber);
nodeQueue.add(node.left);
            }
if (index==parts.length) {
break;
            }
item=parts[index++];
item=item.trim();
if (!item.equals("null")) {
intrightNumber=Integer.parseInt(item);
node.right=newTreeNode(rightNumber);
nodeQueue.add(node.right);
            }
        }
returnroot;
    }
publicstaticStringintegerArrayListToString(List<Integer>nums, intlength) {
if (length==0) {
return"[]";
        }
Stringresult="";
for(intindex=0; index<length; index++) {
Integernumber=nums.get(index);
result+=Integer.toString(number) +", ";
        }
return"["+result.substring(0, result.length() -2) +"]";
    }
publicstaticStringintegerArrayListToString(List<Integer>nums) {
returnintegerArrayListToString(nums, nums.size());
    }
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
Stringline;
while ((line=in.readLine()) !=null) {
TreeNoderoot=stringToTreeNode(line);
List<Integer>ret=newSolution().preorderTraversal(root);
Stringout=integerArrayListToString(ret);
System.out.print(out);
        }
    }
}

image.gif


===========================Talk is cheap, show me the code===========================


目录
相关文章
LeetCode 145. Binary Tree Postorder Traversal
给定一个二叉树,返回它的后序遍历。
71 0
LeetCode 145. Binary Tree Postorder Traversal
|
算法 Java Python
LeetCode 94:二叉树的中序遍历 Binary Tree Inorder Traversal
题目: 给定一个二叉树,返回它的中序 遍历。 Given a binary tree, return the inorder traversal of its nodes' values. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出:...
974 0
LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50930671 翻译 给定一个二叉树,返回其中序遍历的节点的值。
982 0
LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50931535 翻译 给定一个二叉树,返回其前序遍历的节点的值。
880 0