1. 程式人生 > >LeetCode-606. Construct String from Binary Tree (Java)

LeetCode-606. Construct String from Binary Tree (Java)

題目連結

此題是關於二叉樹的,先回顧一下關於二叉樹的相關知識

二叉樹的先序遍歷(根節點,左孩子,右孩子):

public class PreTreeSolution {

    public static String preorderTraversal(TreeNode root) {
    	StringBuilder builder = new StringBuilder(); 
    	//用棧來儲存節點
    	Stack<TreeNode> stack = new Stack<TreeNode>();
    	//根節點入棧
    	stack.push(root);
while(!stack.empty()){ //棧頂元素出棧 TreeNode n = stack.pop(); builder.append(n.val); //由於是 先序,所以讓右節點先入棧 if(n.right != null){ stack.push(n.right); } //左節點再入棧,這樣出棧的時候左節點就可以先出棧 if(n.left != null){ stack.push(n.left); } } return builder.toString(); } public static void main(String[] args) { TreeNode rootNode = new TreeNode(1); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(3); TreeNode node3 = new TreeNode(4); TreeNode node4 = new TreeNode(5); rootNode.left = node1; rootNode.right = node2; node1.left = node3; node1.right = node4; String resultString = preorderTraversal(rootNode); System.out.println(resultString); } } class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int x) { val = x; } }
二叉樹的中序遍歷,(左孩子,根節點,右孩子):
 public static String inorderTraversal(TreeNode root) {
    	StringBuilder builder = new StringBuilder(); 
    	if(root == null){
    		return null;
    	}
    	Stack<TreeNode> stack = new Stack<TreeNode>();
    	TreeNode p =root;
    	while(!stack.isEmpty() || p!=null){
    		if(p!=null){
    			stack.push(p);
    			p = p.left;
} else{ TreeNode t = stack.pop(); builder.append(t.val); p = t.right; } } return builder.toString(); }

二叉樹的後序遍歷(左孩子,右孩子,根節點):
 public static String postOrderTraversal(TreeNode root) {
    	StringBuilder builder = new StringBuilder(); 
    	if(root == null){
    		return null;
    	}
    	Stack<TreeNode> stack = new Stack<TreeNode>();
    	//根節點入棧
    	stack.push(root);
    	while(!stack.isEmpty()){
    		//peek method : Looks at the object at the top of this stack without removing it from the stack.
    		TreeNode temp = stack.peek();
    		//如果節點左右孩子都為空,則出棧輸出值
    		if(temp.left == null && temp.right == null){
    			TreeNode pop = stack.pop();
    			builder.append(pop.val);
    		}
    		else{
    			//如果右孩子不為空,則入棧
    			if(temp.right != null){
    				stack.push(temp.right);
    				//右孩子入棧後置為空。因為節點輸出值時判斷該節點的左右孩子是否為空,
    				//所以如果該節點的右孩子入棧後不置為空,則該節點出棧輸出值時判斷就會出現問題。
    				temp.right = null;
    			}
    			//如果左孩子不為空,則入棧,入棧後左孩子置為空,原因如上
    			if(temp.left != null){
    				stack.push(temp.left);
    				temp.left = null;
    			}
    		}
    	}
    	return builder.toString();
    }

更詳細的內容請戳參考連結

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

則本道題對二叉樹的遍歷屬於先序遍歷。先看程式碼,本程式碼耗時24毫秒,beats 77.8%:

public static String tree2str(TreeNode t) {
    	StringBuilder builder = new StringBuilder(); 
    	if(t == null){
    		return null;
    	}
    	Stack<Object> stack = new Stack<Object>();
    	//根節點入棧
    	stack.push(t);
    	while(!stack.empty()){
    		//棧中包含TreeNode型別的二叉樹節點,也包含String型別的括號
    		Object temp = stack.pop();
    		//判斷是否為TreeNode型別
    		if(temp instanceof TreeNode){
    			TreeNode node = (TreeNode) temp;
    			builder.append(node.val);
    			//如果該節點左右節點都為空,則不執行任何程式碼,否則,執行以下程式碼
    			if(node.left != null || node.right != null){
    				if(node.right != null){
            			stack.push(")");
            			stack.push(node.right);
            			stack.push("(");
            		}
            		if(node.left != null){
            			stack.push(")");
            			stack.push(node.left);
            			stack.push("(");
            		}else{
            			stack.push(")");
            			stack.push("(");
            		}

    			}
    		}
    		//判斷是否為String型別
    		if(temp instanceof String){
    			//String型別直接拼接到builder
    			builder.append((String) temp);
    		}
       	}
    	return builder.toString();
    }


相關推薦

LeetCode-606. Construct String from Binary Tree (Java)

題目連結 此題是關於二叉樹的,先回顧一下關於二叉樹的相關知識 二叉樹的先序遍歷(根節點,左孩子,右孩子): public class PreTreeSolution { public static String preorderTraversal(TreeNod

[Leetcode] Binary tree-- 606. Construct String from Binary Tree

between bstr exce out sts elif ide hole enc You need to construct a string consists of parenthesis and integers from a binary tree with t

[LeetCode&Python] Problem 606. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represe

LeetCode606. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be r

Leetcode PHP題解--D92 606. Construct String from Binary Tree

D92 606. Construct String from Binary Tree 題目連結 606. Construct St

606. Construct String from Binary Tree

type break elf nsh tps self. question ssa -o https://leetcode.com/problems/construct-string-from-binary-tree/#/description You need t

606. Construct String from Binary Tree 【easy】

new mos pen you image color emp same exce 606. Construct String from Binary Tree 【easy】 You need to construct a string consists of paren

606. Construct String from Binary Tree(python+cpp)

題目: You need to construct a string consists of parenthesis and integers from a binary tree with the

leetcodeConstruct String from Binary Tree

Title:Construct String from Binary Tree    606 Difficulty:Easy 原題leetcode地址:https://leetcode.com/problems/construct-string-from-b

606. Construct String from Binary Tree - Easy

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represe

LeetCode - Construct String from Binary Tree

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) :

LeetCode Construct String from Binary Tree 根據二叉樹建立字串

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be

[LeetCode] Construct String from Binary Tree 根據二叉樹建立字串

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be repre

Leetcode606.Construct String from Binary Tree根據二叉樹建立字串

你需要採用前序遍歷的方式,將一個二叉樹轉換成一個由括號和整陣列成的字串。 空節點則用一對空括號 "()" 表示。而且你需要省略所有不影響字串與原始二叉樹之間的一對一對映關係的空括號對。 示例 1: 輸入: 二叉樹: [1,2,3,4]      

Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be repre

[Algorithm] Construct String from Binary Tree

empty exc pla ces color pty ddr put ole You need to construct a string consists of parenthesis and integers from a binary tree with the p

[LeetCode] 104. Maximum Depth of Binary Tree Java

font from max clas [] 高度 java ret 使用 題目: Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the

[LeetCode] 331. Verify Preorder Serialization of a Binary Tree Java

sep find with har ted 分支 input enc equal 題目: One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-nu

Leetcode 366. Find Leaves of Binary Tree

oot mov end res removing self. elf 一個 emp Given a binary tree, collect a tree‘s nodes as if you were doing this: Collect and remove all l

LeetCode】【Python】Binary Tree Inorder Traversal

nod 不知道 otto div ack return integer neu else Given a binary tree, return the inorder traversal of its nodes‘ values. For example: Gi