The original question is as follows:
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
My algorithm:
1. Get the height of the tree first
2. Sequence recursion traversal binary tree (left to right)
The implementation is as follows:
PackageLeetcode;ImportJava.util.ArrayList;ImportJava.util.List; Public class solution { //Get the height of two fork tree, using recursive algorithm, simple and practical intDepth (TreeNode root) {intres =0;if(root==NULL){return 0; }intL = Depth (root.left);intr = Depth (root.right); res = Math.max (l, R) +1;returnRes }//The height of the current layer is level, using recursive algorithm, simple and practical, list for the final result list, //list parameters (Java objects as parameters), can be considered as reference passing, in the method of the list modification, can //affect the final list voidLevelorder (TreeNode root,intLevel,list<list<integer>> List) {if(root==NULL){return; }intToindex = List.size ()-1; List.get (Toindex-level). Add (Root.val);//recursive recursive traversal of binary tree from left to rightLevelorder (root.left,level+1, list); Levelorder (root.right,level+1, list); } PublicList<list<integer>>Levelorderbottom(TreeNode Root) {Arraylist<list<integer>> res =NewArraylist<list<integer>> ();intDep = depth (root); for(intI=0; i<dep;i++) {arraylist<integer> T =NewArraylist<integer> (); Res.add (t); } levelorder (Root,0, res);returnRes } Public Static void Main(string[] args) {TreeNode T = treenode.getdefaulttree (); list<list<integer>> res =NewArraylist<list<integer>> (); Solution s =NewSolution (); res = S.levelorderbottom (t); for(intI=0; I<res.size (); i++) {System.out.println (Res.get (i)); } }}
The code for TreeNode is as follows:
PackageLeetcode; Public class TreeNode { intVal TreeNode left; TreeNode right; TreeNode (intX) {val = x; }//Get a default tree, as in the above question Public StaticTreeNodeGetdefaulttree() {TreeNode T1 =NewTreeNode (3); TreeNode t2 =NewTreeNode (9); TreeNode t3 =NewTreeNode ( -); TreeNode T4 =NewTreeNode ( the); TreeNode T5 =NewTreeNode (7); T1.left = T2; T1.right = t3; T3.left = T4; T3.right = T5;returnT1; }}
Original title address: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
Binary Tree level Order traversal II